package com.lekang.controller;

import com.lekang.common.annotation.Anonymous;
import com.lekang.common.core.domain.AjaxResult;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
@Anonymous
@RestController
@RequestMapping("/phoneLogin")
@CrossOrigin // 开发时允许跨域，生产环境需配置具体域名（如 @CrossOrigin("https://你的小程序域名")）
public class PhoneNumberController {

    // 替换成你自己的小程序 AppID 和 AppSecret！！！
    private static final String APP_ID = "wx45e45510a4a65a29";
    private static final String APP_SECRET = "073ce0e2dcffe8bdf82edd0a582a0b23";

    // 获取 access_token 的接口地址
    private static final String ACCESS_TOKEN_URL =
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    // 获取手机号的接口地址
    private static final String GET_PHONE_NUMBER_URL =
            "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";

    /**
     * 前端调用：传入手机号 code，返回解密后的手机号
     */
    @PostMapping("/getPhoneNumber")
    public AjaxResult getPhoneNumber(@RequestBody PhoneCodeRequest request) {
        String code = request.getCode();

        // 用 try-with-resources 自动关闭 HttpClient（避免资源泄漏）
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 1. 先获取 access_token（小程序全局凭证）
            String accessToken = getAccessToken(httpClient);

            // 2. 调用微信接口，用 code 换手机号
            String phoneApiUrl = String.format(GET_PHONE_NUMBER_URL, accessToken);
            HttpPost httpPost = new HttpPost(phoneApiUrl);

            // 构造请求体（JSON 格式：{"code":"前端传的code"}）
            JSONObject requestBody = new JSONObject();
            requestBody.put("code", code);
            StringEntity entity = new StringEntity(
                    requestBody.toString(),
                    ContentType.APPLICATION_JSON // 指定 Content-Type 为 application/json
            );
            httpPost.setEntity(entity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 解析响应体（微信返回的 JSON 字符串）
                String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("微信返回的手机号数据：" + responseBody);

                // 用 fastjson 解析 JSON，提取手机号（可选，也可直接返回原始数据给前端）
                JSONObject resultJson = JSONObject.parseObject(responseBody);
                if (resultJson.getInteger("errcode") == 0) {
                    // 解析成功：返回手机号（格式：{"phoneNumber":"138xxxx8888"}）
                    JSONObject phoneInfo = resultJson.getJSONObject("phone_info");
                    String phone=phoneInfo.getString("phoneNumber");
                    System.out.println(phone);
                    return new AjaxResult();
                } else {
                    // 解析失败：返回微信的错误信息
                    return new AjaxResult();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult();
        }
    }

    /**
     * 辅助方法：获取 access_token
     */
    private String getAccessToken(CloseableHttpClient httpClient) throws Exception {
        String accessTokenUrl = String.format(ACCESS_TOKEN_URL, APP_ID, APP_SECRET);
        HttpGet httpGet = new HttpGet(accessTokenUrl);

        // 执行请求并解析响应
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println("微信返回的 access_token 数据：" + responseBody);

            JSONObject resultJson = JSONObject.parseObject(responseBody);
            Integer errcode = resultJson.getInteger("errcode");
            if (errcode != null && errcode != 0) {
                // access_token 获取失败（如 AppID/Secret 错误）
                throw new RuntimeException("获取 access_token 失败：" + responseBody);
            }

            // 返回 access_token（有效期 2 小时，生产环境建议缓存，避免频繁调用）
            return resultJson.getString("access_token");
        }
    }

    /**
     * 接收前端传来的 code（POJO 类，用于接收 JSON 参数）
     */
    public static class PhoneCodeRequest {
        private String code;

        // Getter 和 Setter（必须有，Spring 才能自动注入参数）
        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }
    }
}